<form action="data_add_batch.php?<?echo $data['url_parameter']?>"
      class="layui-form"
      method="post">

    <blockquote class="layui-elem-quote">内容数量将会由时间段内，生成指定数量的推文</blockquote>

<div class="select-box clearfix">


    <div class="layui-form-item ">
        <label class="layui-form-label">accesstoken</label>

        <div class="layui-input-block">
            <input type="text" name="accesstoken" id="accesstoken" value="<?echo $_REQUEST['accesstoken']?>" class="layui-input" />
        </div>

        <!--        <span class="layui-btn" id="renew_accesstoken">⬅刷新</span>-->
    </div>

    <div class="layui-form-item ">
        <label class="layui-form-label">公共主页</label>
        <div class="layui-input-block">
            <select name="page_id" id="page_id" lay-verify="required" lay-search="" class="layui-select">
                <?if($_REQUEST['page_id']){?>
                    <option value="<?echo $_REQUEST['page_id']?>"><?echo $optionsArray[$_REQUEST['page_id']]?></option>
                <?;}?>
                <option value="104932918958782">wedding invitation</option>
                <option value="580202941837101">Wholesale of Wedding Planner</option>
                <option value="607371405782562">Wholesale of wedding decor</option>
                <option value="596855730183461">Wholesale of Wedding Guest Book</option>
                <option value="640785835778820">Enping Audio Factory</option>
                <option value="577799722076689">Custom Wedding Crafts</option>
            </select>
        </div>
    </div>

</div>







<blockquote class="layui-elem-quote">推文主要内容由头尾中间内容组成，勾选的内容，将会随机组合。</blockquote>


<div class="select-box clearfix">


    <div class="layui-col-xs4">

    <div class="layui-form-item">
        <label class="layui-form-label">开头：</label>
        <br class="clearfloat"/>
        <div class="content_list">
            <?foreach ($_content_head as $key=>$value){?>
                <div
                        onmouseover="show_remark('<?echo addslashes(str_replace(["\r", "\n"], ['\\r', '\\n'], $value['content']))?>', 'content_part_<?echo $value['nid']?>')"
                        onmouseout="closed_remark('content_<?echo $value['nid']?>')"
                        id='content_part_<?echo $value['nid']?>' >
                    <input type="checkbox" value="<?echo $value['nid']?>"
                           title="<?echo substr($value['content'],0,55)?>..."
                           name="content_head[]" lay-skin="primary"
                           <?if(in_array($value['nid'],$_content_chose_head_nid_array)){echo 'checked';}?>
                    ></div>

                <?;}?>
        </div>
        <em class="explain">固定的头部内容</em>
    </div>

    </div>



    <div class="layui-col-xs4">

        <div class="layui-form-item">
            <label class="layui-form-label">中间内容：</label>
            <br class="clearfloat"/>
            <div class="content_list">
                <?foreach ($_content_body as $key=>$value){?>
                    <div
                            onmouseover="show_remark('<?echo addslashes(str_replace(["\r", "\n"], ['\\r', '\\n'], $value['content']))?>', 'content_part_<?echo $value['nid']?>')"
                            onmouseout="closed_remark('content_part_<?echo $value['nid']?>')"
                            id='content_part_<?echo $value['nid']?>' >
                        <input type="checkbox" value="<?echo $value['nid']?>"
                               title="<?echo substr($value['content'],0,55)?>..."
                               name="content_body[]"
                               lay-skin="primary"
                            <?if(in_array($value['nid'],$_content_chose_body_nid_array)){echo 'checked';}?>
                        ></div>

                    <?;}?>
            </div>
            <em class="explain">固定的头部内容</em>
        </div>

    </div>


    <div class="layui-col-xs4">

        <div class="layui-form-item">
            <label class="layui-form-label">结尾：</label>
            <br class="clearfloat"/>
            <div class="content_list">
                <?foreach ($_content_end as $key=>$value){?>
                    <div
                            onmouseover="show_remark('<?echo addslashes(str_replace(["\r", "\n"], ['\\r', '\\n'], $value['content']))?>', 'content_part_<?echo $value['nid']?>')"
                            onmouseout="closed_remark('content_part_<?echo $value['nid']?>')"
                            id='content_part_<?echo $value['nid']?>' >
                        <input type="checkbox" value="<?echo $value['nid']?>"
                               title="<?echo substr($value['content'],0,55)?>..."
                               name="content_end[]"
                               lay-skin="primary"
                            <?if(in_array($value['nid'],$_content_chose_end_nid_array)){echo 'checked';}?>
                        ></div>

                    <?;}?>
            </div>
            <em class="explain">固定的头部内容</em>
        </div>
    </div>






</div>


<blockquote class="layui-elem-quote">内容数量将会由时间段内，生成指定数量的推文</blockquote>


<div class="select-box clearfix">



        <div class="layui-form-item search-period">
            <label class="layui-form-label">时间段</label>

            <div class="layui-input-block">
                <input type="text" name="greater_startdate"
                       placeholder="请输入开始时间" autocomplete="off"
                       class="layui-input laydate_time"
                       value="<?echo $start_time?>" >
                <span>-</span>
                <input type="text" name="less_enddate"
                       placeholder="请输入结束时间"
                       autocomplete="off"
                       class="layui-input laydate_time"
                       value="<?echo $end_time?>"  >
            </div>
        </div>

        <div class="layui-form-item ">
            <label class="layui-form-label">周期(分钟)</label>

            <div class="layui-input-block">
                <input type="text" name="ai_period"
                       value="<?if($_REQUEST['ai_period']){echo $_REQUEST['ai_period'];}
                                else{echo 60;};?>"
                       class="layui-input" />
            </div>
        </div>

        <div class="layui-form-item ">
            <label class="layui-form-label">偏差</label>

            <div class="layui-input-block">
                <input type="text" name="ai_deviation" value="<?if($_REQUEST['ai_deviation']){echo $_REQUEST['ai_deviation'];}
                else{echo 12;};?>" class="layui-input" />
            </div>
            <em class="explain">将会在最终生成时间，增加或者减小0至此值的时间</em>

        </div>


</div>






<!--===============================-->
<!--标签设置-->
<!--===============================-->



<blockquote class="layui-elem-quote">选择要生成标签的数量以及标签组</blockquote>

<div class="select-box clearfix layui-form">

    <div class="layui-col-xs9">

            <label class="layui-form-label">标签组：</label>
            <br class="clearfloat"/>
            <div class="content_list" style="line-height: 24px;">
                <?foreach ($_content_tag as $key=>$value){?>
                    <span class="layui-badge layui-bg-green" style="cursor: pointer"
                          onclick="check_checkbox('<?echo $value['name'] ?>')" >
                        <?echo $value['name'] ?> </span>

                    <br/>
                    <?
                    $_item_tag=explode(";",$value['content']);

                    foreach ($_item_tag as $k => $v){?>
                        <input type="checkbox" name="tag[]" js-attr="<?echo $value['name'] ?>"
                               lay-skin="primary"
                               value="<?echo $v?>"     title="<?echo $v?>"
                            <? if(in_array($v,$now_tag_array) or (count($now_tag_array)<2))   {echo "checked";} ?>>
                        <?;}?>
                        <hr/>
                    <br class="clearfloat"/>
                    <?;}?>
            </div>
        <em class="explain">所有标签组的标签，都会被加入到标签候选中</em>
    </div>

<script>
    // 添加 check_checkbox 函数，用于切换具有相同 js-attr 属性的复选框选中状态
    function check_checkbox(attrValue) {
        // 查找所有具有指定 js-attr 属性值的复选框
        var checkboxes = $("input[js-attr='" + attrValue + "']");

        // 检查是否有任何复选框被选中
        var anyChecked = checkboxes.is(":checked");

        // 如果有任何一个被选中，则全部取消选中；否则全部选中
        checkboxes.prop("checked", !anyChecked);

        // 重新渲染layui表单元素
        layui.use('form', function(){
            var form = layui.form;
            form.render('checkbox');
        });
    }
</script>



    <div class="layui-col-xs3">

    <div class="layui-form-item ">
        <label class="layui-form-label">标签数</label>

        <div class="layui-input-block">
            <select name="tag_amount" id="tag_amount" lay-verify="required" class="layui-select">
                <?if($tag_amount){?>
                    <option value="<?echo $tag_amount?>"><?echo $tag_amount?></option>
                    <?;}?>
                <option value="1">1</option>
                <?for($i=2;$i<=10;$i++){?>
                <option value="<?echo $i?>"><?echo $i?></option>
                <?;}?>

            </select>
            <em class="explain">每篇推文中，都会添加的标签数</em>

        </div>
    </div>

    </div>



</div>





<input name="creat_switch" type="hidden" value="on" />



<div class="layui-form-item">
        <button type="submit" class="layui-btn" >生成推文</button>

<!--        <span class="layui-btn" type="submit" id="set_sheet_time">构建时间表</span>-->
<!--        <span class="layui-btn" type="submit" id="set_sheet_tag">构建标签</span>-->
<!--        <span class="layui-btn" type="submit" id="set_sheet_content">构建内容</span>-->
        <span class="layui-btn" type="submit" id="set_sheet_folder">统一图片</span>
</div>




</form>



<br/>
<br/>






<script>


    //点击renew_accesstoken，获取新的accesstoken
    $("#renew_accesstoken").click(function () {
        console.log("点击了renew_accesstoken");
        $.ajax({
            url: "https://graph.facebook.com/oauth/access_token?client_id=1781511916033621&client_secret=060f800db76860a54714b9e9c2b8a46f&grant_type=client_credentials",
            type: "get",
            dataType: "json",
            success: function(response) {
                console.log("response"+response);

                if (response.access_token) {
                    // 更新页面上的accesstoken
                    //返回的结果格式是这样的{
                    //    "access_token": "1781511916033621|ESbJOeCp70Yi5fNKst9tZAEQ-qc",
                    //    "token_type": "bearer"
                    //}
                    var accesstoken = response.access_token;
                    console.log("accesstoken"+accesstoken);

                    $("#accesstoken").val(accesstoken);

                }
            }
            ,error: function(response) {
                console.log("请求失败：", response);
            }
        })
    });

    // 定义 set_all_tag 函数在全局作用域中
    function set_all_tag(){
        // 检查第一个复选框的状态
        var isChecked = $("input[name='ai_wedding_tag[]']:first").prop("checked");

        // 根据第一个复选框的状态进行全选或取消全选
        $("input[name='ai_wedding_tag[]']").each(function(){
            $(this).prop("checked", !isChecked);
        });

        layui.use('form', function(){
            var form = layui.form;
            form.render('checkbox'); // 重新渲染 checkbox
        });
    }


    $("#set_sheet_time").click(function () {
        // 获取输入的开始日期和结束日期
        var greater_startdate = $("input[name='greater_startdate']").val();
        //提取这个字符串中，表示 小时 的数值
        var start_hour = greater_startdate.split(" ")[1].split(":")[0];
        console.log(start_hour);

        var less_enddate = $("input[name='less_enddate']").val();

        // 检查日期是否有效
        if (greater_startdate && less_enddate) {
            var start_date = new Date(greater_startdate);
            var end_date = new Date(less_enddate);

            // 计算时间范围内的总天数
            var total_days = Math.ceil((end_date - start_date) / (1000 * 60 * 60 * 24));

            // 遍历每一天，生成日期并填充到输入框中
            for (var i = 0; i < total_days; i++) {
                // 计算当前日期
                var current_date = new Date(start_date.getTime() + i * 24 * 60 * 60 * 1000);
                //current_date 的小时 设置成 start_hour
                current_date.setHours(start_hour);
                console.log("改时时"+current_date);


                var current_date_str = current_date.toISOString(); // 格式化为 YYYY-MM-DD
                // current_date_str  随机增减40分钟
                var randomMinutes = Math.floor(Math.random() * 80) - 40; // 生成-40到40之间的随机数
                var current_date = new Date(current_date_str);
                console.log("随机时"+current_date);


                current_date.setMinutes(current_date.getMinutes() + randomMinutes);
                console.log("setMinutes"+current_date);

                current_date_str = current_date.toLocaleString().slice(0, 19).replace(/\//g, '-').replace('T', ' '); // 格式化为 YYYY-MM-DD HH:MM:SS
                console.log("输出结果"+current_date_str);


                // 填充对应的 publish_date[] 输入框
                $("input[name='publish_date[]']").eq(i).val(current_date_str);
            }
        } else {
            console.error("Please enter valid start and end dates.");
        }
    });




    // 根据ai_wedding_tag勾选的项目，随机抽取3个，按照顺序填写到ai_tag[]输入框中
    $("#set_sheet_tag").click(function () {
        var checkedTags = [];
        $("input[name='ai_wedding_tag[]']:checked").each(function(){
            checkedTags.push($(this).val());
        });
        if (checkedTags.length >= 3) {
            // 获取所有 ai_tag[] 输入框
            var aiTagInputs = $("input[name='ai_tag[]']");
            aiTagInputs.each(function() {
                // 随机抽取3个标签
                var randomTags = checkedTags.sort(() => Math.random() - 0.5).slice(0, 3);
                // 设置到当前 ai_tag[] 输入框
                $(this).val(randomTags.join(' '));
                console.log(randomTags);
            });
            //alert("随机抽取的标签已填写到ai_tag输入框中。");
        } else {
            alert("请至少勾选3个标签。");
        }
    });




    //set_sheet_folder 点击此元素，统一调整图片文件夹
    $("#set_sheet_folder").click(function ()
    {
        //根据data_form中第一个select的ai_media[]选择的值，其他所有ai_media[]都设置成一样
        var firstValue = $("select[name='ai_media[]'] option:selected").val();
        console.log("firstValue"+firstValue);
        $("select[name='ai_media[]']").each(function(){
            $(this).val(firstValue);
        });


        layui.use('form', function(){
            var form = layui.form;
            form.render('select'); // 重新渲染 checkbox
        });

    });




    //set_sheet_content 点击此元素，出发构建内容
    //访问api内容，返回内容，填充到ai_content输入框中
    $("#set_sheet_content").click(function () {
        //弹出遮罩图层，用于等待
        show_message_layer();

        //传输ai_content的内容到/api/system/tongyiqianwen/common_result.php,获取返回数据
        $.ajax({
            url: '/api/system/tongyiqianwen/common_result.php',
            type: 'POST',
            data: {
                ai_prefix: $("textarea[name='ai_prefix']").val(),
                ai_content: $("textarea[name='ai_content']").val(),
                ai_sum: $("input[name='ai_sum']").val()
            },
            success: function(response) {
                //返回的结果中，提取出内容，填充到ai_content输入框中
                console.log(response);

                //response.data 为数组，循环填充到ai_content输入框中
                for (var i = 0; i < response.data.length; i++) {
                    //如果是空内容，则跳过
                    if (response.data[i] == "") {
                        continue;
                    }
                    else
                    {
                        $("textarea[name='ai_content[]']").eq(i).val(response.data[i]);

                        //把ai_basic的内容添加到ai_content输入框的中内容的后面
                        $("textarea[name='ai_content[]']").eq(i).val($("textarea[name='ai_prefix']").val() + "\n\n" + $("textarea[name='ai_content[]']").eq(i).val() + "\n\n" + $("textarea[name='ai_basic']").val());



                    }

                }

                hide_message_layer();

            }
        });
    });

    //layui渲染过的元素，需要在这里写函数
    layui.use('form', function(){
        var form = layui.form;
    });
</script>

